package com.fg.cloud.manager.service.agency.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.manager.entry.BaseEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.product.ProductSkuEntity;
import com.fg.cloud.manager.entry.product.vo.ProductInfoVo;
import com.fg.cloud.manager.entry.product.vo.ProductSkuVo;
import com.fg.cloud.manager.entry.system.AgencyCartEntity;
import com.fg.cloud.manager.entry.system.TrolleyEntity;
import com.fg.cloud.manager.entry.system.vo.AgencyCartVo;
import com.fg.cloud.manager.entry.system.vo.AgencyNewCartVo;
import com.fg.cloud.manager.entry.system.vo.TrolleyVo;
import com.fg.cloud.manager.mapper.BaseMapper;
import com.fg.cloud.manager.mapper.agency.AgencyCartMapper;
import com.fg.cloud.manager.mapper.agency.AgencyMapper;
import com.fg.cloud.manager.service.BaseServiceImpl;
import com.fg.cloud.manager.service.agency.AgencyCartService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * Description:购物车Service实现类
 * @author dingjiang
 * @date 2017年8月28日上午11:39:59
 */
@Service
public class AgencyCartServiceImpl extends BaseServiceImpl implements AgencyCartService {
	
	@Autowired
	private AgencyCartMapper agencyCartMapper;

	@Override
	protected <T extends BaseEntity> BaseMapper getBaseMapper() {
		return agencyCartMapper;
	}

	
	@Override
	public Long findCount(Long ageId) {
		return agencyCartMapper.findCount(ageId);
	}


	/**
	 * 判断要添加的商品skuId和unitId是否已存在
	 */
	@Override
	public boolean filter(AgencyCartVo cartVo) {
		return agencyCartMapper.filter(cartVo) > 0 ? true : false ;
	}

	/**
	 * 数量累加
	 */
	@Override
	@Transactional
	public boolean addAmount(AgencyCartVo cartVo,Long updater) {
		return agencyCartMapper.addAmount(cartVo, updater) > 0 ? true : false;
	}


	/**
	 * 查询同种sku数量之和
	 */
	@Override
	public List<TrolleyEntity> findAmount(Long skuId) {
		
		return agencyCartMapper.findAmount(skuId);
	}

	
	@Override
	public boolean deleteAll(Long ageId) {
		return agencyCartMapper.deleteAll(ageId) > 0 ? true : false;
	}
	
	/**
	 * 删除指定的购物车记录
	 */
	@Override
	@Transactional
	public boolean deletes(Long ageId, Long[] ids) {
		return agencyCartMapper.deletes(ageId, ids)>0 ? true : false ;
	}
	
	/**
	 * 根据skuId删除指定的购物车记录
	 */
	@Override
	public boolean deleteBySku(Long ageId, Long[] ids) {
		return agencyCartMapper.deleteBySku(ageId, ids)>0 ? true : false ;
	}
	

	/**
	 * 加入购物车
	 */
	@Override
	@Transactional
	public boolean insert(ProductInfoVo entity, AgencyUserVo user) {
		//读取SKU信息
		ProductSkuVo sku = entity.getSku();
		
		
		AgencyCartEntity cart = new AgencyCartEntity();
		cart.setFacId(user.getFacId()); 
		cart.setAgeId(user.getAgeId());
		cart.setProductId(entity.getId());
		cart.setSkuId(sku.getId());
		cart.setAmount(sku.getAmount());
		cart.setUnitId(sku.getUnitId());
		cart.setPromotionPrice(sku.getSpecialPrice());
		cart.setIsCustom(entity.getIsCustom());
		cart.setBatchNumber(null);
		cart.setCreator(user.getId());
		cart.setUpdater(user.getId());
		
		/*trolley.setProductSpec("【".concat(
				sku.getProductSpec().replaceAll("[{}\" ]+", "")).concat("】"));*/

		return agencyCartMapper.insertSelective(cart) > 0 ? true : false;
	}

	@Override
	public void findList(PageUtils<AgencyCartVo> pageInfo, AgencyUserVo user) {
		long total = agencyCartMapper.findCount(user.getAgeId());
		pageInfo.setTotal(total);
		if (0 == total) {
			pageInfo.setData(new ArrayList<AgencyCartVo>());
			return;
		}
		//经销商等级折扣
		BigDecimal discount = user.getDiscount().multiply(BigDecimal.valueOf(0.01));
		//全局是否启用订货权限
		Integer placeorder = user.getPlaceorder();
		
		List<AgencyCartVo> cartList = agencyCartMapper.findList(pageInfo);
		
		for (AgencyCartVo entity : cartList) {
			//若没有换算数量，则默认给1
			if (null == entity.getStdAmount()) entity.setStdAmount(1);
			
			//判断全局是否启用订货权限，1=启用
			if (1 == user.getPlaceorder() && 0 == entity.getAuthority()) {
				entity.setIsEnabled(0);
			}
			//判断是否库存不足，全局不开启无库存接单
			if (0 == user.getStockSetup().getZeroFlag() &&
					entity.getStock().doubleValue() <= 0) {
				entity.setIsEnabled(0);
			}
			//判断是否还存在该SKU-unitID的商品
			if (!entity.getUnitId().equals(entity.getStdUnitId())) {
				if (1 == entity.getMultiUnit()) {
					//当不存在多单位记录时
					if (StringUtils.isEmpty(entity.getPmUnitName())) {
						entity.setIsEnabled(0);
					} 
				} else {//当没有开启多单位时
					entity.setIsEnabled(0);
				}
			}
			
			//判断SKU状态
			if (1 != entity.getSkuStatus()) entity.setIsEnabled(0);
			//判断单位状态
			if (1 != entity.getUnitStatus()) entity.setIsEnabled(0);
			
			//若存在经销商特价则取特价乘换算数量
			if (null != entity.getAssignPrice()) {
				entity.setPromotionPrice(entity.getAssignPrice().multiply(
						BigDecimal.valueOf(entity.getStdAmount())));
			} else {
				//判断是否有多单位优惠特价,没有则取原价换算等级折扣
				if (1 == entity.getMultiUnit() && null != entity.getCustomPrice()) {
					entity.setPromotionPrice(entity.getCustomPrice().multiply(discount));
				} else {
					entity.setPromotionPrice(entity.getSellPrice().multiply(discount));
				}
			}
			entity.setBasicPrice(entity.getPromotionPrice());
			//小计价格
			entity.setSumMoney(entity.getPromotionPrice().multiply(entity.getAmount()));
		}
		
		//拆分可编辑与不可编辑的数据
		List<AgencyCartVo> returnData = Lists.newArrayList();
		List<AgencyCartVo> enableData = Lists.newArrayList();
		for(AgencyCartVo entity : cartList) {
			if (1 == entity.getIsEnabled()) returnData.add(entity);
			else enableData.add(entity);
		}
		if (enableData.size() > 0)
			returnData.addAll(enableData);
		
		pageInfo.setData(returnData);
	}

	@Override
	public List<TrolleyEntity> findAll(Long ageId) {
		// TODO Auto-generated method stub
		return null;
	}

	
	
	
	

	public static void main(String[] args) {
		String str = "{\"品牌\":\"农夫山泉\",\"品种\":\"血橙\"}";
		System.out.println("【".concat(str.replaceAll("[{}\" ]+", "")).concat("】"));
	}
}
